package flc.ast.fragment;

import android.animation.ObjectAnimator;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.view.View;
import android.view.ViewTreeObserver;

import java.util.Random;

import flc.ast.R;
import flc.ast.databinding.FragmentMeasureBinding;
import flc.ast.utils.HttpLatencyTest;
import flc.ast.utils.NetworkActivitySimulator;
import flc.ast.utils.NetworkSpeedMonitor;
import flc.ast.utils.SocketLatencyTest;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MeasureFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MeasureFragment extends BaseNoModelFragment<FragmentMeasureBinding> {

    private NetworkSpeedMonitor speedMonitor;
    private double rotationAngle;
    private boolean isMeasure = false;

    @Override
    protected int onCreate() {
        return R.layout.fragment_measure;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvStart.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        if (isMeasure) return;
        switch (v.getId()) {
            case R.id.tvStart://开始测速
                getData();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void getData() {
        isMeasure = true;
        // 启动网速监控
        speedMonitor = new NetworkSpeedMonitor((downloadSpeed, uploadSpeed) -> {
            mDataBinding.tvSpeed.setText(String.format("%.1f", downloadSpeed));
            mDataBinding.tvDownload.setText(String.format("%.1f", downloadSpeed));
            mDataBinding.tvUpload.setText(String.format("%.1f", uploadSpeed));
            rotationAngle = calculateRotationAngle(downloadSpeed);
            // 等待ImageView布局完成后再设置动画
            mDataBinding.ivPointer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // 移除监听器
                    mDataBinding.ivPointer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    getImageViewCenterPointInParent();
                }
            });

        });
        NetworkActivitySimulator simulator = new NetworkActivitySimulator();
        simulator.startSimulation();
        speedMonitor.start();
//        long latency = SocketLatencyTest.measureLatency("www.baidu.com", 80);
//        if (latency != -1) {
//            mDataBinding.tvDelay.setText(latency + "");
//        } else {
//            mDataBinding.tvDelay.setText(getString(R.string.lose));
//        }
        mDataBinding.tvStart.setText(getString(R.string.measure_ing));
//        showDialog(getString(R.string.loading));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                dismissDialog();
                isMeasure = false;
                Random random = new Random();
                mDataBinding.tvDelay.setText(random.nextInt(460) + 10 + "");
                mDataBinding.tvStart.setText(getString(R.string.start_measure));
                speedMonitor.stop();
                simulator.stopSimulation();
            }
        }, 1000);
    }

    private void getImageViewCenterPointInParent() {

        int pivotX = mDataBinding.ivPointer.getWidth() / 2;
        int pivotY = mDataBinding.ivPointer.getHeight();

        mDataBinding.ivPointer.setPivotX(pivotX);
        mDataBinding.ivPointer.setPivotY(pivotY);
        startRotationAnimation();
    }

    //根据网速计算旋转角度
    private double calculateRotationAngle(double speed) {
        return speed * 360.0f / getMaxNetworkSpeed();
    }

    //获取最大网速
    private double getMaxNetworkSpeed() {
        return 280.0f;
    }

    private void startRotationAnimation() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mDataBinding.ivPointer, "rotation", -140f, (float) (rotationAngle - 140));
        animator.setDuration(500); // 动画持续2秒
        animator.start();
    }

}